import Router from 'koa-router'
import axios from 'axios'
import Poi from '../db/models/Poi'

let router = new Router({ prefix: '/search' })

router.get('/top', async ctx => {
  const { name, city } = ctx.request.query
  // const top = await Poi.find({
  //   name: new RegExp(name),
  //   city
  // })
  // ctx.body = {
  //   code: 0,
  //   top: top.map(({ name, type }) => ({ name, type }))
  // }
  // noinspection JSAnnotator
  const {
    status,
    data: { data }
  } = await axios.get(
    `https://www.meituan.com/ptapi/suggest?keyword=${encodeURIComponent(name)}`
  )
  if (status == 200 && data && data.suggestItems.length) {
    ctx.body = {
      code: 0,
      top: data.suggestItems.map(({ query }) => ({ name: query }))
    }
  } else {
    ctx.body = {
      code: 0,
      top: []
    }
  }
})

router.get('/hotPlace', async ctx => {
  const city = ctx.store ? ctx.store.geo.position.city : ctx.request.query.city
  const res = await Poi.find({
    city
  }).limit(4)
  ctx.body = {
    code: 0,
    hotPlace: res.map(({ name, type }) => ({ name, type }))
  }
})

router.get('/resultByKeyword', async ctx => {
  const { keyword, city } = ctx.request.query
  const {
    status,
    data: { data }
  } = await axios.get(
    `https://apimobile.meituan.com/group/v1/area/search/${encodeURIComponent(
      city
    )}`
  )
  if (status != 200 || !data.length) {
    ctx.body = {
      code: 0,
      pois: []
    }
  }
  const cityid = data[0].cityId
  const {
    status: stu,
    data: {
      data: { searchResult }
    }
  } = await axios.get(
    `http://apimobile.meituan.com/group/v4/poi/pcsearch/${cityid}`,
    {
      headers: {
        'User-Agent':
          'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
      },
      params: {
        uuid: '1f915be4690f4ddf89b9.1546503089.1.0.0',
        userid: -1,
        limit: 32,
        offset: 0,
        cateId: -1,
        q: encodeURIComponent(keyword)
      }
    }
  )
  if (stu == 200 && searchResult.length) {
    const pois = searchResult.map(item => {
      return {
        id: item.id,
        type: `${item.backCateName}|${item.areaname}`,
        img: item.imageUrl.replace('/w.h', '') + '@220w_125h_1e_1c',
        name: item.title,
        comment: item.comments,
        rate: Number(item.avgscore),
        price: Number(item.avgprice),
        scene: [],
        tel: item.tel || '',
        status: '可订明日',
        location: [item.longitude, item.latitude],
        addr: item.address,
        module: []
      }
    })
    ctx.body = {
      code: 0,
      pois
    }
  } else {
    ctx.body = {
      code: 0,
      pois: []
    }
  }
})

router.get('/product', async ctx => {
  const { id } = ctx.request.query
  const res = await axios.get(`https://www.meituan.com/cate/${id}/`, {
    headers: {
      'User-Agent':
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
    }
  })
  if (res.status == 200 && /window._appState = ({.+})?/g.exec(res.data)) {
    const match = /window._appState = ({.+})?/g.exec(res.data)
    const j = JSON.parse(match[1])
    const {
      photos: { albumImgUrls },
      detailInfo: { name, avgScore, avgPrice, address, phone },
      dealList: { deals }
    } = j
    ctx.body = {
      code: 0,
      product: {
        name,
        rating: avgScore,
        cost: avgPrice,
        address: address,
        tel: phone,
        photos: albumImgUrls || []
      },
      list: deals.reduce(
        (total, { frontImgUrl, title, soldNum, deadline, price, value }) => {
          total.push({
            url: frontImgUrl,
            name: title,
            soldNum,
            deadline: new Date(deadline),
            price,
            value
          })
          return total
        },
        []
      ),
      login: ctx.isAuthenticated()
    }
  } else if (res.status == 200 && /window.AppData = ({.+})?/g.exec(res.data)) {
    const match = /window.AppData = ({.+})?/g.exec(res.data)
    const j = JSON.parse(match[1])
    const {
      album,
      poiInfo: { name, score, avgPrice, address, phone },
      groupDealList: { group }
    } = j
    ctx.body = {
      code: 0,
      product: {
        name,
        rating: score,
        cost: avgPrice,
        address: address,
        tel: phone,
        photos: album.reduce((photos, { url }) => {
          photos.push(url)
          return photos
        }, [])
      },
      login: ctx.isAuthenticated(),
      list: group.reduce(
        (total, { headIcon, title, sold, deadline, price, value }) => {
          total.push({
            url: headIcon,
            name: title,
            sold,
            deadline: new Date(deadline),
            price,
            value
          })
          return total
        },
        []
      )
    }
  } else {
    ctx.body = {
      code: 0,
      product: {},
      login: ctx.isAuthenticated()
    }
  }
})

export default router
